<script setup lang="ts">
import common from "_s/common/localstore";
const lang = common.getLang();
const { locale } = useI18n({ useScope: "global" });

import languages from "quasar/lang/index.json";
const $q = useQuasar();
if (lang) {
  locale.value = lang as string;
}

const diyLang = ["zh-CN", "en-US"];

// const modules = import.meta.glob('../../node_modules/quasar/lang/(de|en-US|es).js')

const modules = import.meta.glob("../../../node_modules/quasar/lang/(zh-CN|en-US).js");

const appLanguages = languages.filter(lang => diyLang.includes(lang.isoName));

const langOptions = appLanguages.map(lang => ({
  label: lang.nativeName,
  value: lang.isoName
}));

const menu = ref();
const changeLang = (languages: string) => {
  locale.value = languages;
  common.setLang(languages);
  menu.value.hide();

  const moduleKey = `../../../node_modules/quasar/lang/${languages}.js`;
  if (modules[moduleKey]) {
    void modules[moduleKey]().then(lang => {
      // @ts-expect-error: lang.default type may not match expected type
      $q.lang.set(lang.default);
    });
  } else {
    console.warn(`Language module not found: ${moduleKey}`);
  }
};
</script>

<template>
  <!-- @mouseenter="showLanguages -->
  <q-btn
    flat
    size="sm"
    padding="sm"
    round
    icon="translate"
  >
    <!-- {{ $t("components.i18n.title") }} -->
    <q-menu
      transition-show="jump-down"
      ref="menu"
      transition-hide="jump-up"
    >
      <q-list style="min-width: 100px">
        <q-item
          :active="locale === item.value"
          clickable
          v-for="item in langOptions"
          :key="item.value"
          active-class="my-menu-link"
          @click="changeLang(item.value)"
        >
          <q-item-section>{{ item.label }}</q-item-section>
        </q-item>
      </q-list>
    </q-menu>
  </q-btn>
</template>

<style lang="scss" scoped>
.my-menu-link {
  background-color: var(--q-primary);
  color: white;
}

.q-item {
  min-height: 32px;
  font-size: 12px;
}
</style>
